package com.young.consul.health;

import com.ecwid.consul.v1.ConsulClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.actuate.health.Health;
import org.springframework.cloud.consul.ConsulHealthIndicator;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryClient;

/**
 * Consul自定义健康检查
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2020/12/2
 */
public class ConsulHealthIndicatorOverride extends ConsulHealthIndicator {
    private final Log log = LogFactory.getLog(ConsulDiscoveryClient.class);

    private ConsulClient consul;

    private long threshold;

    public ConsulHealthIndicatorOverride(ConsulClient consul, long threshold) {
        super(consul);
        this.consul = consul;
        this.threshold = threshold;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        try {
            if (HealthCheckStatic.checkCount < threshold) {
                builder.up().withDetail("consul-client-self", "passing")
                        .withDetail("checkCount", HealthCheckStatic.checkCount++);
            } else {
                builder.down().withDetail("consul-client-self", "critical")
                        .withDetail("checkCount", HealthCheckStatic.checkCount++);
            }
            log.info(String.format("/actuator/health/consul %s", HealthCheckStatic.checkCount));
            //todo 条件
            //throw new Exception("健康检查异常测试");
        } catch (Exception e) {
            NoSuchBeanDefinitionException noSuchBeanDefinitionException = new NoSuchBeanDefinitionException("consulHealthIndicator", e.getMessage());
            builder.down().withDetail("consul-client-self", "critical");
        }
    }
}
